package com.dragonfly.shutter.services;

import java.util.Date;

import com.dragonfly.shutter.DAOs.AlbumDAO;
import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.PictureAlbumDAO;
import com.dragonfly.shutter.DAOs.PictureDAO;
import com.dragonfly.shutter.beans.Album;
import com.dragonfly.shutter.beans.BrowseLog;
import com.dragonfly.shutter.beans.PictureAlbum;

/**
 * 移动图片服务类
 * @author 黄挺
 */
public class MovePictureService {
	private AlbumDAO albumDAO;
	private PictureAlbumDAO pictureAlbumDAO;
	private BrowseLogDAO browseLogDAO;
	private PictureDAO pictureDAO;

	/**
	 * 移动图片服务函数
	 * @param userID 用户ID
	 * @param pictureID 图片ID
	 * @param albumID 原始相册ID
	 * @param desAlbumID  目标相册ID
	 * @param requestURL 请求URL
	 */
	public void doService(Integer userID, String pictureID, Integer albumID,
			Integer desAlbumID, String requestURL) {
		BrowseLog browseLog = new BrowseLog(userID, new Date(System.currentTimeMillis()), requestURL);
		PictureAlbum srcPictureAlbum = new PictureAlbum();
		PictureAlbum desPictureAlbum = new PictureAlbum();
		
		srcPictureAlbum.setAlbumID(albumID);
		srcPictureAlbum.getPictureBrief().setPictureID(pictureID);
		desPictureAlbum.setAlbumID(desAlbumID);
		desPictureAlbum.getPictureBrief().setPictureID(pictureID);
		
		doDBOperate(srcPictureAlbum, desPictureAlbum, browseLog);
	}
	
	/**
	 * 移动图片数据库操作函数
	 * @param srcPictureAlbum 原始相册图片关联Bean
	 * @param desPictureAlbum 目标相册图片关联Bean
	 * @param browseLog 日志Bean
	 */
	private void doDBOperate(PictureAlbum srcPictureAlbum,
			PictureAlbum desPictureAlbum, BrowseLog browseLog) {
		pictureAlbumDAO.deletePictureAlbumByPK(srcPictureAlbum);
		Album srcAlbum = albumDAO.selectAlbumByID(srcPictureAlbum.getAlbumID());
		srcAlbum.setPictureCount(srcAlbum.getPictureCount() - 1);
		albumDAO.updatePictureCount(srcAlbum);
		
		pictureAlbumDAO.insertPictureAlbum(desPictureAlbum);
		Album desAlbum = albumDAO.selectAlbumByID(desPictureAlbum.getAlbumID());
		
		if( desAlbum.getPictureCount() == 0 ){
			String thumbLocation =pictureDAO.selectPicBriefByPicId(desPictureAlbum.getPictureBrief().getPictureID()).getThumbLocation();
			albumDAO.updateEnvelopPicId(desAlbum.getAlbumID(), 
					thumbLocation);
		}
		
		desAlbum.setPictureCount(desAlbum.getPictureCount() + 1);
		albumDAO.updatePictureCount(desAlbum);
		browseLogDAO.insertBrowseLog(browseLog);
	}

	public void setAlbumDAO(AlbumDAO albumDAO) {
		this.albumDAO = albumDAO;
	}

	public AlbumDAO getAlbumDAO() {
		return albumDAO;
	}

	public void setPictureAlbumDAO(PictureAlbumDAO pictureAlbumDAO) {
		this.pictureAlbumDAO = pictureAlbumDAO;
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}

	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}
}
